﻿using Longbow.Cache;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace Longbow.Web
{
    /// <summary>
    /// 在线用户服务实现类
    /// </summary>
    internal class DefaultOnlineUsers : IOnlineUsers
    {
        private readonly ConcurrentDictionary<string, AutoExpireCacheEntry<OnlineUser>> _onlineUsers = new ConcurrentDictionary<string, AutoExpireCacheEntry<OnlineUser>>();
        private readonly IIPLocatorProvider _locator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="locator"></param>
        public DefaultOnlineUsers(IIPLocatorProvider locator)
        {
            _locator = locator;
        }

        /// <summary>
        /// 获得 当前在线用户集合
        /// </summary>
        /// <returns></returns>
        public IEnumerable<OnlineUser> OnlineUsers
        {
            get { return _onlineUsers.Values.Select(v => v.Value); }
        }

        /// <summary>
        /// 添加或者更新在线用户信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="addValueFactory"></param>
        /// <param name="updateValueFactory"></param>
        /// <returns></returns>
        public AutoExpireCacheEntry<OnlineUser> AddOrUpdate(string key, Func<string, AutoExpireCacheEntry<OnlineUser>> addValueFactory, Func<string, AutoExpireCacheEntry<OnlineUser>, AutoExpireCacheEntry<OnlineUser>> updateValueFactory) => _onlineUsers.AddOrUpdate(key, addValueFactory, updateValueFactory);

        /// <summary>
        /// 移除现在用户信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="onlineUserCache"></param>
        /// <returns></returns>
        public bool TryRemove(string key, out AutoExpireCacheEntry<OnlineUser> onlineUserCache) => _onlineUsers.TryRemove(key, out onlineUserCache);
    }
}
